package com.yidao.repository.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.yidao.core.service.impl.BaseServiceImpl;
import com.yidao.repository.service.RepositoryService;

@Service
public class FileRepositoryService extends BaseServiceImpl implements RepositoryService{
	
	private String repositoryPath = null;
	
	private List<String> categories = new ArrayList<String>();
	
	public FileRepositoryService(){
		
		this.getLogger().debug("FileRepositoryService init.");
		
		this.repositoryPath = "/home/feng/yidao";
		
		this.categories.add("templates");
		this.categories.add("uploads");
		this.categories.add("temps");
		this.categories.add("images");
		this.categories.add("documents");
		this.initFileSystem();
	}
	
	private void initFileSystem() {
		File rootPath = new File(this.repositoryPath);
		
		this.getLogger().debug("try to create " + this.repositoryPath);
		this.getLogger().debug(!rootPath.exists() || !rootPath.isDirectory());
		if(!rootPath.exists() || !rootPath.isDirectory()){
			rootPath.mkdirs();
		}
		this.getLogger().debug(rootPath.exists());
		
		for(String category:this.categories){
			File categoryDir = new File(rootPath + File.separator + category);
			if(!categoryDir.exists() || !categoryDir.isDirectory()){
				categoryDir.mkdirs();
			}
		}
	}

	@Override
	public Object getObject(String name, String category) {
		String filePath = this.repositoryPath + File.separator + category + File.separator + name;
		File targetFile = new File(filePath);
		return targetFile;
	}

	@Override
	public void putObject(String name, String category, Object object) {
		
		String filePath = this.repositoryPath + File.separator + category + File.separator + name;
		File targetFile = new File(filePath);
		if(targetFile.exists()){
			targetFile.delete();
		}
		
		try {
			FileOutputStream out = new FileOutputStream(targetFile);
			InputStream in = (InputStream)object;
			
			byte[] buffer = new byte[8192];
			while(true){
				int byteReaded = in.read(buffer);
				if(byteReaded == 8192){
					out.write(buffer);
				}else{
					out.write(buffer, 0, byteReaded);
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void addCategory(String category) {
		categories.add(category);
	}

	@Override
	public List<String> listCategories() {
		return this.categories;
	}

	@Override
	public void removeObject(String name, String category) {
		String filePath = this.repositoryPath + File.separator + category + File.separator + name;
		File targetFile = new File(filePath);
		if(targetFile.exists()){
			targetFile.delete();
		}
	}
}
